import axios from "axios";
import { useUserStore } from "@/stores";
import { ElMessage } from 'element-plus'


let userStore;
/**
 * 单位ip
 */
const url = "http://192.168.101.35:8080/";
/**
 * 家里ip
 */
// const url = "http://192.168.0.116:8080/";


const api = axios.create({
  baseURL: url,
});

// 请求拦截器
api.interceptors.request.use(
  config => {
    userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = userStore.token;
    }
    return config;
  },
  (err) => {
    return Promise.reject(err);
  }
);

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (err) => {
    if (err.response && err.response.status === 401) {
      ElMessage({
        message: '登录失效，请重新登录',
        type: 'error',
        plain: true,
      })
      userStore = useUserStore()
      userStore.logout()
    }
    return Promise.reject(err);
  }
);

export default api;
